package com.lizy.java;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 虽然是测试代码，但是还有好多优化东西
 */
public class RabbitProducer {
    private static final String EXCHANGE_NAME = "exchange_demo";
    private static final String ROUTING_KEY = "routingkey_demo";
    private static final String QUEUE_NAME = "queue_demo";
    private static final String IP_ADDRESS = "192.168.124.24";
    private static final int PORT = 5672;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(IP_ADDRESS);
        connectionFactory.setPort(PORT);
        connectionFactory.setUsername("root");
        connectionFactory.setPassword("root");
        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection();
            channel = connection.createChannel();
            // 创建一个type为direct， 持久化的，非自动删除的交换器
            channel.exchangeDeclare(EXCHANGE_NAME, "direct",true,false, null);
            // 创建一个持久化的，非排他的，非自动删除的队列
            channel.queueDeclare(QUEUE_NAME, true, false,false,null);
            // 将交换器和队列进行绑定， 路由为： ROUTING_KEY
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
            String message = "Hello World!";
            // 将消息发送到交换器EXCHANGE_NAME中，路由为ROUTING_KEY
            channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
            channel.isOpen();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (null != channel) {
                    channel.close();
                }
                if(null != connection) {
                    connection.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (TimeoutException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
